import logging
import sys

from active_alchemy import ActiveAlchemy

import config

db = ActiveAlchemy('sqlite:///data/db/memedb.db')


class Meme(db.Model):
    # (id existe implicitement avec ActiveAlchemy)
    # id = db.Column(db.Integer, primary_key=True)
    fbid = db.Column(db.String(25), unique=True)
    source = db.Column(db.String(), default="Facebook")
    saved = db.Column(db.Boolean(), default=False)
    path = db.Column(db.String(), nullable=True)
    html_path = db.Column(db.String(), nullable=True)
    info = db.Column(db.String(), nullable=True)
    deadlink = db.Column(db.Boolean(), default=False)
    json = db.Column(db.String(), nullable=True)


db.create_all()


def load_or_create_in_db(fbid):
    logging.debug('Trying with fbid '+fbid)

    # fbid is not primary index

    meme = Meme.query().filter(Meme.fbid == fbid).first()
    if(meme):
        already_exists = True
        logging.debug('fbid '+fbid+' already exists in db')
    else:
        meme = Meme.create(fbid=fbid, source="Neurchi de Template")
        logging.info('Meme '+fbid+' added to db')
        meme.save()

    return meme
